package edu.ccut.saturn.studio.example;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import edu.ccut.saturn.studio.core.exception.XMLException;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnProjectUtil;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnBundleUtil;
import edu.ccut.saturn.studio.core.util.wizard.SaturnWizardPage;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.saturndata.model.DataItem;
import edu.ccut.saturn.studio.saturndata.model.SaturnData;
import edu.ccut.saturn.studio.saturndata.model.SaturnDataModel;

/**
 * 创建简单事例向导页——选择数据项向导页
 * 
 * @author 赵新峰
 * @version 1.0 2009.09
 */

public class SampleWizardPage extends SaturnWizardPage {

	private Text text;
	private Tree tree;
	private String selectedSaturnData;
	private String bundleName;
	private String menuPtah;
	private DataItemAtrributesVO dataItemAtrributesVO = new DataItemAtrributesVO();
	public boolean isPageComplete = true;
	protected static final String SEPARATOR = File.separator;
	public static final String CLASSPATH_IS_TYPE_SRC = "src";
	public static final String CLASSPATH_IS_TYPE_LIB = "lib";
	public static final String SEARCH_NAME_ENDWITH_JAR = "jar";
	private static final String FILECLASSPATH = ".classpath";
	private static final String CLASSPATH_NODE_NAME = "classpathentry";
	private static final String CLASSPATH_ATTRIBUTE_KIND = "kind";
	private static final String CLASSPATH_ATTRIBUTE_PATH = "path";
	private static final String TYPE_FILE_NAME = ".saturn";
	private static final String SATURN_FOLDER_TYPE = "type";
	protected static final String SATURN_FOLDER_MODULE = "module";
	protected static final String MANIFEST_BUNDLE_REQUIRE = "Require-Bundle";
	private static final String MENU_NAME = "menu.config";
	private Map<String, File> SaturnDataFileMap = new HashMap<String, File>();
	private String connectionname;

	public SampleWizardPage(DataItemAtrributesVO dataItemAtrributesVO,
			String string) {
		this.dataItemAtrributesVO = dataItemAtrributesVO;
		setDescription(Messages.getString("SampleWizardPage.chooseDataItem")); //$NON-NLS-1$
	}

	@Override
	public void initalValues(Map<String, Object> values) {

		String primaryKeyName = getSelectedPtrimarykey(
				this.getSaturnDataPrameter()).getName();

		String selectedSaturnDataFullykey = this
				.getSelectedFullkey(SaturnDataFileMap.get(this
						.getSelectedSaturnData()));
		values.put("name", saturnDataName());
		values.put("muen", menuPtah);
		values.put("titaDataValuekey", selectedSaturnDataFullykey);
		values.put("saturnDataNamespace", selectedSaturnDataFullykey.substring(
				0, selectedSaturnDataFullykey.indexOf("::")));
		values.put("saturnDataType", selectedSaturnDataFullykey.substring(
				selectedSaturnDataFullykey.indexOf("::") + 2,
				selectedSaturnDataFullykey.length()));
		values.put("selectedDataItemes", this.getSaturnDataPrameter());
		values.put("selectSaturndataPrimarykey", getSelectedPtrimarykey(this
				.getSaturnDataPrameter()));
		values.put("connectionname", connectionname);

		/**
		 * 查询的参数
		 */
		values.put("queryLogicKey", (File.separator + getPackageName()
				+ File.separator + "logic" + File.separator + "query"
				+ saturnDataName() + ".logic").replace("\\", "/"));

		values.put("queryActionkey", (File.separator + getPackageName()
				+ File.separator + "action" + File.separator + "query"
				+ saturnDataName() + ".action").replace("\\", "/"));

		values.put("queryActionLogickey", (bundleName + "::" + File.separator
				+ getPackageName() + File.separator + "logic" + File.separator
				+ "query" + saturnDataName() + ".logic").replace("\\", "/"));

		values.put("queryActionJspkey", (File.separator + bundleName
				+ File.separator + getPackageName() + File.separator + "web"
				+ File.separator + "query" + saturnDataName() + ".jsp")
				.replace("\\", "/"));

		values.put("queryJspActionkey", (File.separator + bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "query" + saturnDataName() + ".action")
				.replace("\\", "/"));

		values.put("queryJspAddNewJsp", (File.separator + bundleName
				+ File.separator + getPackageName() + File.separator + "web"
				+ File.separator + "add" + saturnDataName() + ".jsp").replace(
				"\\", "/"));

		values.put("queryJspDeleteAction", (File.separator + bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "delete" + saturnDataName() + ".action")
				.replace("\\", "/"));

		values.put("queryJspUpsateAction", (File.separator + bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "queryBy"
				+ changeFristToUpCase(primaryKeyName) + ".action").replace(
				"\\", "/"));

		/**
		 * 按照主键查询
		 * 
		 */
		values.put("queryByPrimaryKeyLogic", (File.separator + getPackageName()
				+ File.separator + "logic" + File.separator + "queryBy"
				+ changeFristToUpCase(primaryKeyName) + ".logic").replace("\\",
				"/"));
		values.put("queryByPrimaryKeyAction", (File.separator
				+ getPackageName() + File.separator + "action" + File.separator
				+ "queryBy" + changeFristToUpCase(primaryKeyName) + ".action")
				.replace("\\", "/"));
		values.put("queryBykeyActionLogickey", (bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "logic"
				+ File.separator + "queryBy"
				+ changeFristToUpCase(primaryKeyName) + ".logic").replace("\\",
				"/"));
		values.put("updateJspkey", (File.separator + bundleName
				+ File.separator + getPackageName() + File.separator + "web"
				+ File.separator + "update" + saturnDataName() + ".jsp")
				.replace("\\", "/"));

		/**
		 * 添加的参数
		 */
		values.put("addLogicKey", (File.separator + getPackageName()
				+ File.separator + "logic" + File.separator + "add"
				+ saturnDataName() + ".logic").replace("\\", "/"));
		values.put("addActionKey", (File.separator + getPackageName()
				+ File.separator + "action" + File.separator + "add"
				+ saturnDataName() + ".action").replace("\\", "/"));
		values.put("addActionResultActionkey", (bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "query" + saturnDataName() + ".action")
				.replace("\\", "/"));
		values.put("addActionLogickey", (bundleName + "::" + File.separator
				+ getPackageName() + File.separator + "logic" + File.separator
				+ "add" + saturnDataName() + ".logic").replace("\\", "/"));

		values.put("addJspaddActionKey", (File.separator + bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "add" + saturnDataName() + ".action")
				.replace("\\", "/"));

		/**
		 * 修改的参数
		 */
		values.put("updateJspUpateAction", (File.separator + bundleName + "::"
				+ File.separator + getPackageName() + File.separator + "action"
				+ File.separator + "update" + saturnDataName() + ".action")
				.replace("\\", "/"));
		values.put("updateLogicKey", (File.separator + getPackageName()
				+ File.separator + "logic" + File.separator + "update"
				+ saturnDataName() + ".logic").replace("\\", "/"));
		values.put("updateActionKey", (File.separator + getPackageName()
				+ File.separator + "action" + File.separator + "update"
				+ saturnDataName() + ".action").replace("\\", "/"));
		values.put("updateActionLogickey", (bundleName + "::" + File.separator
				+ getPackageName() + File.separator + "logic" + File.separator
				+ "update" + saturnDataName() + ".logic").replace("\\", "/"));

		/**
		 * 删除的参数
		 */
		values.put("deleteLogicKey", (File.separator + getPackageName()
				+ File.separator + "logic" + File.separator + "delete"
				+ saturnDataName() + ".logic").replace("\\", "/"));
		values.put("deleteActionkey", (File.separator + getPackageName()
				+ File.separator + "action" + File.separator + "delete"
				+ saturnDataName() + ".action").replace("\\", "/"));
		values.put("deleteActionLogickey", (bundleName + "::" + File.separator
				+ getPackageName() + File.separator + "logic" + File.separator
				+ "delete" + saturnDataName() + ".logic").replace("\\", "/"));
	}

	public String getSelectedSaturnData() {
		return selectedSaturnData;
	}

	public void setSelectedSaturnData(String saturnDataPath) {
		this.selectedSaturnData = saturnDataPath;
	}

	public void createControl(Composite parent) {
		Composite contaniner = new Composite(parent, SWT.NULL);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		contaniner.setLayout(gridLayout);
		contaniner.setSize(40, 50);
		setControl(contaniner);

		final Label label = new Label(contaniner, SWT.NONE);
		label.setText(Messages.getString("SampleWizardPage.selectSaturnData")); //$NON-NLS-1$
		new Label(contaniner, SWT.NONE);
		new Label(contaniner, SWT.NONE);

		tree = new Tree(contaniner, SWT.BORDER);
		final GridData gd_tree = new GridData(SWT.FILL, SWT.FILL, true, true);
		gd_tree.widthHint = 295;
		tree.setLayoutData(gd_tree);
		tree.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				TreeItem item = (TreeItem) e.item;
				text.setText(item.getText());
				setSelectedSaturnData(item.getText());
				setErrorMessage(null);
				setPageComplete(false);
				dataItemAtrributesVO.setDataItems(getSaturnDataPrameter());
				validateDataItemPrimary();
			}
		});

		final Label label_1 = new Label(contaniner, SWT.NONE);
		label_1.setText(Messages.getString("SampleWizardPage.Sure")); //$NON-NLS-1$

		text = new Text(contaniner, SWT.READ_ONLY | SWT.BORDER);
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		IProject project = SaturnProjectUtil.getProject(super.getSelection());
		IResource resource = SaturnProjectUtil
				.getResource(super.getSelection());
		try {
			bundleName = getBundleName(project);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Set<String> srcs = getClassPathsByType(project, CLASSPATH_IS_TYPE_SRC);

		for (String src : srcs) {
			for (File fileMoudle : new File(src).listFiles()) {
				if (fileMoudle.isDirectory()) {
					if ((SATURN_FOLDER_MODULE
							.equals(saturnFileType(fileMoudle)))
							&& (resource.getName().equals(fileMoudle.getName()
									.trim()))) {

						for (File SaturnFoldere : fileMoudle.listFiles()) {

							if (SaturnFoldere.isDirectory()
									&& issaturnDataFileType(SaturnFoldere)) {

								TreeItem treeItem = new TreeItem(tree, SWT.NONE);
								treeItem.setText(SaturnFoldere.getName());

								for (File Saturndata : SaturnFoldere
										.listFiles()) {
									if (Saturndata.getName().endsWith(
											"saturndata")) {
										new TreeItem(treeItem, SWT.NONE)
												.setText(Saturndata.getName());
										treeItem.setExpanded(true);
										SaturnDataFileMap.put(Saturndata
												.getName(), Saturndata);
									}
								}
							}
						}
					}
				}
				if (MENU_NAME.equals(fileMoudle.getName())) {
					menuPtah = fileMoudle.getAbsolutePath();
				}
			}
		}
	}

	/**
	 * 获得被选中数据项的主键
	 * 
	 * @param dataItem
	 *            List<DataItem> dataItems 被选中的数据项
	 * @return 数据项的主键
	 */
	public DataItem getSelectedPtrimarykey(List<DataItem> dataItems) {
		for (DataItem dataItem : dataItems) {
			if ("true".equals(dataItem.getIsPrimaryKey())) {
				return dataItem;
			}
		}
		return null;
	}

	/**
	 * 获得选中的数据项的数据项字段集合
	 * 
	 * @param
	 * @return List<DataItem> dataItems
	 */
	public List<DataItem> getSaturnDataPrameter() {

		List<DataItem> dataItems = null;

		try {
			File selectedSaturnDataPtah = this.SaturnDataFileMap.get(this
					.getSelectedSaturnData());
			Document doc = SaturnW3CUtil.getDocument(selectedSaturnDataPtah
					.getAbsolutePath());
			SaturnDataModel data = new SaturnDataModel(doc);
			SaturnData datas = data.getSaturnData();
			connectionname = datas.getConnectionName();
			dataItems = datas.getDataItemList();
		} catch (XMLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dataItems;
	}

	/**
	 * 指定一个工程获得bundel属性文件里的BundelName
	 * 
	 * @param project
	 * @return
	 */
	protected static String getBundleName(IProject project) throws Exception {
		String path = SaturnBundleUtil.getProjectBundleFile(project).getPath();
		return SaturnBundleUtil.getBundleSymbolicName(path);
	}

	private String getSelectedFullkey(File file) {

		String saturnDataFullykey = "";
		try {

			Document doc = SaturnW3CUtil.getDocument(this.SaturnDataFileMap
					.get(this.getSelectedSaturnData()).getAbsolutePath());
			Node dataNode = SaturnW3CUtil.getFirstChildByName(doc
					.getDocumentElement(), "data");
			String namespace = SaturnW3CUtil.getNodeAttributeValue(dataNode,
					"namespace");
			String name = SaturnW3CUtil.getNodeAttributeValue(dataNode, "name");
			saturnDataFullykey = namespace + "::" + name;

		} catch (XMLException e1) {
			e1.printStackTrace();
		}
		return saturnDataFullykey;
	}

	protected boolean issaturnDataFileType(File path) {
		String typeValue = "";

		String typeFilePath = path.getAbsolutePath() + SEPARATOR
				+ TYPE_FILE_NAME;

		File typeFile = new File(typeFilePath);

		if (typeFile.exists()) {

			try {
				Document doc = SaturnW3CUtil.getDocument(typeFilePath
						.toString());

				if (doc != null) {
					Node root = doc.getDocumentElement();

					typeValue = SaturnW3CUtil.getChildNodeValue(root,
							SATURN_FOLDER_TYPE);
					if ("data".equals(typeValue)) {
						return true;
					}
				}
			} catch (XMLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return false;
	}

	/**
	 * 判断是不是指定类型的文件夹
	 * 
	 * @param path
	 *            文件夹路径
	 * @param type
	 *            要搜索文件类型
	 * @return
	 */
	protected static String saturnFileType(File path) {
		String typeValue = "";

		String typeFilePath = path.getAbsolutePath() + SEPARATOR
				+ TYPE_FILE_NAME;

		File typeFile = new File(typeFilePath);

		if (typeFile.exists()) {

			try {
				Document doc = SaturnW3CUtil.getDocument(typeFilePath
						.toString());

				if (doc != null) {
					Node root = doc.getDocumentElement();

					typeValue = SaturnW3CUtil.getChildNodeValue(root,
							SATURN_FOLDER_TYPE);
				}
			} catch (XMLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return typeValue;
	}

	/**
	 * 根据类型获得类路径
	 * 
	 * @param project,type
	 * 
	 * @return Set<String> paths
	 */
	protected static Set<String> getClassPathsByType(IProject project,
			String type) {
		Set<String> paths = new HashSet<String>();

		try {
			String projectPath = project.getLocation().toOSString();

			String tempPath = projectPath + SEPARATOR + FILECLASSPATH;

			Document document = SaturnW3CUtil.getDocument(tempPath);

			Node root = document.getDocumentElement();
			List<Node> classpathentryNodes = SaturnW3CUtil.getChildrenByName(
					root, CLASSPATH_NODE_NAME);

			if (classpathentryNodes != null) {
				for (Node classpathentryNode : classpathentryNodes) {
					String kind = SaturnW3CUtil.getNodeAttributeValue(
							classpathentryNode, CLASSPATH_ATTRIBUTE_KIND);

					if (type.equals(kind)) {
						final String path = classpathentryNode.getAttributes()
								.getNamedItem(CLASSPATH_ATTRIBUTE_PATH)
								.getNodeValue();
						paths.add(new StringBuffer(projectPath).append(
								SEPARATOR).append(path).toString());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return paths;
	}

	protected String getPackageName() {
		IResource resource = SaturnProjectUtil
				.getResource(super.getSelection());

		String packageName = resource.getProjectRelativePath().toOSString();
		packageName = packageName
				.substring(packageName.indexOf(File.separator) + 1);
		packageName = packageName.replace(File.separator, "/");

		return packageName;
	}

	/**
	 * 新建的文件名称中的SaturnData名称规范
	 */
	public String saturnDataName() {

		String saturnDataName = selectedSaturnData.substring(0,
				selectedSaturnData.indexOf("."))
				+ "Saturndata";
		return changeFristToUpCase(saturnDataName);

	}

	public String changeFristToUpCase(String str) {
		return (str.substring(0, 1).toUpperCase() + str.substring(1, str
				.length()));
	}

	/**
	 * 验证所选择的数据项所设主键的个数。如果未设主键，提示选择一个主键；如果主键的个数大于一个，提示选择的数据项
	 * 中所含主键的个数，并提示只能选择一个主键。
	 * 
	 * @param
	 * @return
	 */
	public void validateDataItemPrimary() {
		List<DataItem> selectedDataItems = dataItemAtrributesVO.getDataItems();
		int count = 0;
		setPageComplete(true);
		for (DataItem dataItem : selectedDataItems) {
			if ("true".equals(dataItem.getIsPrimaryKey())) {
				count++;
			}
		}
		if (count == 0) {
			setErrorMessage(Messages.getString("SampleWizardPage.noPrimaryKey")); //$NON-NLS-1$
			setPageComplete(false);
		}
		if (count > 1) {
			setErrorMessage(Messages.getString(Messages
					.getString("SampleWizardPage.11")) //$NON-NLS-1$
					+ count
					+ Messages.getString("SampleWizardPage.manyPrimaryKey2")); //$NON-NLS-1$ //$NON-NLS-2$
			setPageComplete(false);
		}
	}
}
